package com.zy.mall.service;

import com.zy.mall.dao.GoodDaoImpl;
import com.zy.mall.dao.GoodsDao;
import com.zy.mall.model.Goods;
import com.zy.mall.model.Spec;
import com.zy.mall.model.Type;
import com.zy.mall.model.bo.GoodsBo;
import com.zy.mall.model.bo.SpecBo;
import com.zy.mall.model.vo.TypeGoodsVo;

import java.util.ArrayList;
import java.util.List;

public class GoodServiceImpl implements GoodService {

    private GoodsDao goodsDao = new GoodDaoImpl();

    @Override
    public List<Type> getType() {
        return goodsDao.getType();
    }

    @Override
    public List<TypeGoodsVo> getGoodsByType(String typeId) {
        return goodsDao.getGoodsByType(typeId);
    }

    @Override
    public void addGoods(GoodsBo goodsBo) {
        List<SpecBo> specList = goodsBo.getSpecList();
        double price = specList.get(0).getUnitPrice();
        int stockNum = specList.get(0).getStockNum();
        for (int i = 1; i < specList.size(); i++) {
            if (price > specList.get(i).getUnitPrice()) {
                price = specList.get(i).getUnitPrice();
            }
            if (stockNum < specList.get(i).getStockNum()) {
                stockNum = specList.get(i).getStockNum();
            }
        }
        Goods goods = new Goods(null, goodsBo.getImg(), goodsBo.getName(), price, goodsBo.getTypeId(), stockNum, goodsBo.getDesc());
        goodsDao.addGoods(goods);
        int id = goodsDao.lastInsertId();
        List<Spec> specs = new ArrayList<>();
        for (SpecBo specBo : specList) {
            Spec spec = new Spec(null, specBo.getSpacName(), specBo.getStockNum(), specBo.getUnitPrice(), id);
            specs.add(spec);
        }
        goodsDao.addSpecs(specs);
    }

    @Override
    public int addType(Type name) {
        return goodsDao.addType(name);
    }
}
